<template>
	<a-modal v-bind="option">
		<vxe-table ref="grid" class="rent-out-print-grid" :cell-class-name="cellClassName" :show-header="false" border :column-config="{resizable: true}" :align="reportInfo.allAlign" :merge-cells="reportInfo.mergeCells" :data="reportInfo.tableData">
			<vxe-column field="name" title="" align="left"></vxe-column>
			<vxe-column field="desc" title=""></vxe-column>
			<vxe-column field="name1" title=""></vxe-column>
			<vxe-column field="desc1" title=""></vxe-column>
			<vxe-column field="desc2" title=""></vxe-column>
		</vxe-table>
		<iframe id="print" v-if="grid" hidden width="100%" scrolling="no" frameborder="0" />
	</a-modal>
</template>

<script setup lang="ts">
	import {reactive, toRef, ref, watch, nextTick, onUnmounted} from 'vue'
	import {VxeTablePropTypes, VxeTableInstance} from 'vxe-table'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import fileApi from 'yuxin-base/src/api/file-api'
	import {getConcreteRecord} from '@/api/contract'
	import dayjs from 'dayjs'

	const props = defineProps<{
		visible: boolean
		data: any
	}>()
	const grid = ref<VxeTableInstance>()
	const detail = ref<any>({})
	let $print = null

	const infoConfig = reactive({
		tableData: [],
		mergeCells: []
	})

	const reportInfo = reactive({
		allAlign: 'center',
		size: 'small',
		tableData: infoConfig.tableData,
		rowConfig: {
			height: 60
		},
		mergeCells: infoConfig.mergeCells as VxeTablePropTypes.MergeCells
	})

	const emits = defineEmits(['update:visible'])

	const option = reactive({
		title: '打印退租报告',
		width: 800,
		scrollX: {enabled: false},
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		footer: null,
		visible: toRef(props, 'visible'),
		bodyStyle: {
			padding: '20px 16px',
			maxHeight: '500px',
			overflowY: 'auto'
		},
		onCancel() {
			emits('update:visible', false)
		}
	})

	const printFun = el => {
		$print.contentWindow.print()
	}

	const downloadTable = () => {
		$print = document.querySelector('#print') as HTMLIFrameElement
		if ($print.contentDocument && $print.contentWindow) {
			$print.contentDocument.head.innerHTML = document.head.innerHTML
			$print.contentDocument.body.innerHTML = grid.value?.$el.outerHTML
			setTimeout(() => {
				$print.contentDocument.addEventListener('load', printFun(), false)
			}, 500)
		}
	}

	// 生成账单列表
	const createBillColumn = billArr => {
		// 账单列表
		const billTotal = []
		billArr.forEach(i => {
			i.bills.forEach(j => {
				billTotal.push({name: i.name, desc: Number(j.totalAmount || 0).toFixed(2), name1: j.comment, desc1: j.billDate, desc2: '', col: 3, rowspan: 1, colspan: 2})
			})
		})
		// 总计
		const total = billTotal.reduce((prev, curr) => {
			return prev + Number(curr.desc)
		}, 0)

		billTotal.push({name: '总计', desc: total.toFixed(2), name1: '', desc1: '', desc2: '', row: 19, col: 1, rowspan: 1, colspan: 5})
		return billTotal
	}

	// 生成处理信息记录
	const createDealRecord = DealArr => {
		const mapApprovalResult = {
			2: '驳回',
			3: '通过'
		}
		const dealRecord = [
			{name: '处理信息记录', desc: '', name1: '', desc1: '', desc2: '', row: 20, col: 0, rowspan: 1, colspan: 5},
			{name: '处理人', desc: '处理步骤', name1: '审核意见', desc1: '处理结果', desc2: '处理时间'}
		]
		;(DealArr || []).forEach(i => {
			dealRecord.push({
				name: i.approvalPersonName,
				desc: mapApprovalResult[i.approvalResult],
				name1: i.comment,
				desc1: mapApprovalResult[i.approvalResult],
				desc2: i.approvalTime
			})
		})
		return dealRecord
	}

	const cellClassName: VxeTablePropTypes.CellClassName = ({row}) => {
		if ('退租报告' === row.name) {
			return 'print-report-title'
		}
		if (['处理时间', '处理结果', '审核意见', '处理步骤', '处理人', '创建时间', '费用备注', '费用金额', '费用名称', '业务信息', '账单信息', '处理信息记录'].includes(row.name)) {
			return 'print-report-sub-title'
		}
		return null
	}

	const isEmpty = str => {
		return str ? str : ''
	}

	const loadTableData = async info => {
		const getBillColumn = createBillColumn(info.billInfos || [])
		const {house, renterInfo} = info
		const contractType = {
			31: '正常退',
			32: '违约退',
			33:'协议退'
		}
		// 获取附件名字
		const belongingsFile = await fileApi.getFileList(info.id)
		const fileNameStr = belongingsFile.data.map((i, index) => `${index + 1}、${i.fileOriginName}`).join(' ')
		// 获取处理记录
		let recordList = []
		try {
			const dealRecord = await getConcreteRecord({approvalType: 30, businessId: info.id})
			if (dealRecord.data && dealRecord.data.length) {
				recordList = createDealRecord(dealRecord.data)
			}
		} catch (error) {
			console.log('未获取到流程记录')
		}

		const hasBusinessNumber = info.contractNo ? [{name: '退租业务编号', desc: dayjs(info.contractNo), name1: '', desc1: '', desc2: '', row: 3, col: 1, rowspan: 1, colspan: 5}] : [{}]

		const newTableData = [
			{name: '退租报告', desc: '', name1: '', desc1: '', desc2: '', row: 0, col: 0, rowspan: 2, colspan: 5},
			{name: '', desc: '', name1: '', desc1: '', desc2: ''},
			// 业务信息
			{name: '业务信息', desc: '', name1: '', desc1: '', desc2: '', row: 2, col: 0, rowspan: 1, colspan: 5},
			{name: '退租业务编号', desc: `TZ${dayjs(info.cancelInfo.rejectTime).format('YYYYMMDDHHmm')}`, name1: '', desc1: '', desc2: '', row: 3, col: 1, rowspan: 1, colspan: 5},
			{name: '退租日期', desc: formatDate(info.quiteDate), name1: '退租类型', desc1: contractType[info.contractStatus], desc2: '', row: 4, col: 3, rowspan: 1, colspan: 2},
			{name: '业务门店', desc: isEmpty(info.signDeptName), name1: '业务管家', desc1: isEmpty(info.maintainerName), desc2: '', row: 5, col: 3, rowspan: 1, colspan: 2},
			{name: '房屋位置', desc: isEmpty(house.address), name1: '', desc1: '', desc2: '', row: 6, col: 1, rowspan: 1, colspan: 5},
			{name: '租户名称', desc: isEmpty(renterInfo.name), name1: '租户电话', desc1: isEmpty(renterInfo.phone), desc2: '', row: 7, col: 3, rowspan: 1, colspan: 2},
			{name: '收款账户类型', desc: 1 === info?.cancelInfo?.paymentAccountType ? '银联' : '个人', name1: '收款账户名称', desc1: isEmpty(renterInfo.name), desc2: '', row: 8, col: 3, rowspan: 1, colspan: 2},
			{name: '收款行行号', desc: info?.cancelInfo?.bankNumber || '/', name1: '收款银行账号', desc1: info?.cancelInfo?.paymentAccount || '/', desc2: '', row: 9, col: 3, rowspan: 1, colspan: 2},
			{name: '收款账户银行', desc: info?.cancelInfo?.bankName || '/', name1: '', desc1: '', desc2: '', row: 10, col: 1, rowspan: 1, colspan: 5},
			{name: '租期', desc: `${isEmpty(info.beginTime)}至${isEmpty(info.endTime)}`, name1: '', desc1: '', desc2: '', row: 11, col: 1, rowspan: 1, colspan: 5},
			{name: '附件', desc: fileNameStr, name1: '', desc1: '', desc2: '', row: 12, col: 1, rowspan: 1, colspan: 5},
			// 账单信息
			{name: '账单信息', desc: '', name1: '', desc1: '', desc2: '', row: 13, col: 0, rowspan: 1, colspan: 5},
			{name: '费用名称', desc: '费用金额', name1: '费用备注', desc1: '创建时间', desc2: '', row: 14, col: 3, rowspan: 1, colspan: 2},
			...getBillColumn,
			// 处理信息记录
			...recordList
		]

		reportInfo.tableData = newTableData
		reportInfo.mergeCells = setRowConfig(newTableData)

		setTimeout(()=>{
			downloadTable()
		})
	}

	// 配置合并列(table中有的用table中的 没有的话默认)
	const setRowConfig = tableData => {
		const megerConfig = []
		tableData.forEach((i, idx) => {
			if (i.col || 0 === i.col) {
				megerConfig.push({row: idx, col: i.col, rowspan: i.rowspan, colspan: i.colspan})
			}
		})
		return megerConfig
	}

	watch(
		() => props.data,
		newVal => {
			detail.value = newVal
			loadTableData(newVal)
		},
		{deep: true}
	)

	defineExpose({
		downloadTable
	})

	onUnmounted(() => {
		if ($print) {
			$print.removeEventListener('load', printFun)
		}
	})
</script>

<style lang="less">
	@media print {
		.rent-out-print-grid {
			width: 800px;
		}

		.rent-out-print-grid .vxe-table--header,
		.rent-out-print-grid .vxe-table--body {
			font-size: inherit;
		}

		.rent-out-print-grid .vxe-table--body-wrapper {
			overflow: hidden;
		}

		.print-report-title {
			text-align: center;
			font-weight: bold;
			font-size: 26px;

			.vxe-cell {
				text-align: center;
			}
		}

		.print-report-sub-title {
			font-weight: bold;
		}
	}

	.print-report-title {
		text-align: center;
		font-weight: bold;
		font-size: 26px;

		.vxe-cell {
			text-align: center;
		}
	}

	.print-report-sub-title {
		font-weight: bold;
	}
</style>
